/* ****************************************************************************
 * Copyright (c) TCC - 2009 IME - USP. 
 *
 * This source code is subject to terms and conditions of the Microsoft Public License. 
 * A copy of the license can be found in http://msdn.microsoft.com/en-us/library/dd228915.aspx. 
 * By using this source code in any fashion, you are agreeing to be bound by the terms of the 
 * Microsoft Public License.
 *
 * You must not remove this notice, or any other, from this software.
 * ***************************************************************************/

namespace SoundLibrary
{
    internal sealed class Crc16
    {
        private static short polynomial;
        private short crc;

        #region Constructor
        static Crc16()
        {
            polynomial = (short)SupportClass.Identity(0x8005);
        }

        public Crc16()
        {
            this.crc = (short)SupportClass.Identity(0xFFFF);
        }
        #endregion

        #region Public Methods

        public void Add_bits(int bitstring, int length)
        {
            int bitmask = 1 << (length - 1);
            do
            {
                if (((this.crc & 0x8000) == 0) ^ ((bitstring & bitmask) == 0))
                {
                    this.crc <<= 1;
                    this.crc ^= polynomial;
                }
                else
                {
                    this.crc <<= 1;
                }
            }
            while ((bitmask = SupportClass.URShift(bitmask, 1)) != 0);
        }

        public short Checksum()
        {
            short sum = this.crc;
            this.crc = (short)SupportClass.Identity(0xFFFF);
            return sum;
        }
        #endregion
    }
}